#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
#include <arpa/inet.h>

#define PORT 8080
#define SERVER_IP "127.0.0.1"
struct pthread_param
{
  int* socket_desc;
  struct sockaddr_in* addr;
};
void *connection_handler(void *);

int main() {
    int sockfd;
    struct sockaddr_in serv_addr;
    pthread_t thread_id;

    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("ERROR opening socket");
        exit(1);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    serv_addr.sin_port = htons(PORT);

    if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
        perror("ERROR connecting");
        exit(1);
    }
    struct pthread_param param;
    param.addr = &serv_addr;
    param.socket_desc = &sockfd;
    if (pthread_create(&thread_id, NULL, connection_handler, (void*) &param) < 0) {
        perror("ERROR on thread creation");
        return 1;
    }

    pthread_join(thread_id, NULL);

    close(sockfd);
    return 0;
}

void *connection_handler(void *pparam) {
    struct pthread_param param = *(struct pthread_param*)pparam;
    int sock = *(param.socket_desc);
    struct sockaddr_in server_addr = *(param.addr);
    char buffer[256];
    char bufferOut[512];
    char serverId[256];
    bzero(buffer, 256);
    bzero(serverId, 256);
    sprintf(serverId, "Server IP: %s, Port: %d",inet_ntop(AF_INET, &(server_addr.sin_addr.s_addr), buffer, 
        sizeof(buffer)), ntohs(server_addr.sin_port));
    printf("[Conect] Thread: %d, %s\n", getpid(), serverId);
    
    bzero(buffer, 256);
    //read(sock, buffer, 255);
    recv(sock, buffer, sizeof(buffer), 0);
    printf("[Receive from server %s]: %s\n", serverId, buffer);
    while(strcmp("stop\n", buffer) != 0){
        printf("Please enter the message: ");
        bzero(buffer, 256);
        fgets(buffer, 255, stdin);
        send(sock, buffer, sizeof(buffer), 0);
        //write(sock, buffer, strlen(buffer));
        printf("[Send to server %s]: %s\n", serverId, buffer);
        recv(sock, bufferOut, sizeof(bufferOut), 0);
        //read(sock, bufferOut, 511);
        printf("[Receive from server %s]: %s\n", serverId, bufferOut);        
    }
    printf("[Close]\n");
    return 0;
}

